package com.laoli.lab39;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;

/**
 * 发生异常与捕获异常的时效性示例
 */
public class ExceptionTimeliness {
    public static void main(String[] args) throws InterruptedException {
        // 异步任务
        CompletableFuture<Object> task = CompletableFuture.supplyAsync(() -> {
                    //return new Random().nextInt(10) + 1;
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.printf("【异步任务】发生异常：%s\n",
                            LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                    throw new RuntimeException("taskAException");
                })
                .handle((result, exception) -> {
                    if(exception!=null){
                        System.out.printf("【handle】捕获异常：%s\n",
                                LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        throw new RuntimeException(exception.getCause().getMessage());
                    }
                    return result;
                })
                .exceptionally(exception -> {
                    System.out.printf("【exceptionally】捕获异常：%s\n",
                            LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                    return 0;
                });
        // 主线程休眠
        Thread.sleep(5000);
    }
}
